<!--
 * @Author: egg1bro
 * @Date: 2023-01-10 15:50:29
 * @LastEditTime: 2023-01-14 12:02:41
 * @LastEditors: egg1bro
 * @Description: 
 * @FilePath: \team-graduation-design\src\views\personInfo\updatePhone.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
    <!-- 导航栏 -->
    <div class="nav">
        <van-nav-bar title="修改手机号">
            <template #left>
                <van-icon name="arrow-left" size="20" color="#3c3c3c" @click="goManageAccount" />
            </template>
        </van-nav-bar>
    </div>
    <div class="body">
        <van-cell-group inset>
            <!-- 输入手机号，调起手机号键盘 -->
            <van-field v-model="tel" type="tel" placeholder="新手机号" clearable />
            <van-field v-model="sms" center clearable placeholder="请输入短信验证码">
                <template #button>
                    <van-button size="small" type="primary" @click="startTimer" :disabled="timeLeft > 0"
                        v-if="timeLeft == 0">发送验证码</van-button>
                    <span v-else="timeLeft > 0">{{ timeLeft + "s后重新获取" }}</span>
                </template>
            </van-field>
        </van-cell-group>

    </div>
    <!-- 登录按钮 -->
    <div class="lgbtn" @click="submitPhone">
        <van-button square block type="primary" native-type="submit">
            登录
        </van-button>
    </div>


</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUpdateUserInfo } from '@/stores/updateUserInfo'
// 实例化路由
const router = useRouter()
// 实例化仓库
const updateUserInfo = useUpdateUserInfo()

const { getSmsByToken, getUpdateUserPhone } = updateUserInfo

// 设置默认验证码倒计时
const timeLeft = ref(0)
let timer = null

const tel = ref('')

const sms = ref('')
// to 账号管理页面
const goManageAccount = () => {
    router.push('/manageAccount')
}

// 倒计时开始 并获取验证码
const startTimer = async () => {

    if (timeLeft.value === 0) {
        timeLeft.value = 60
    }
    timer = setInterval(() => {
        if (timeLeft.value > 0) {
            timeLeft.value--;
        } else {
            clearInterval(timer);
        }
    }, 1000);
    try {
        await getSmsByToken(tel.value)
    } catch (error) {
        return Promise.reject(error)
    }
}

// 提交手机号和验证码
const submitPhone = async () => {
    try {
        await getUpdateUserPhone({ sms: sms.value, phone: tel.value })
    } catch (error) {
        return Promise.reject(error)
    }
}

</script>

<style lang="less" scoped>
.lgbtn {
    margin: 30px 30px 10px 30px;
}
</style>